/**
 * @file WechatController.java
 * @project spring-wechat
 * @copyright 无锡雅座在线科技发展有限公司
 */
package com.mark.controller;

import com.mark.constant.CommonMsg;
import com.mark.constant.ConstantValue;
import com.mark.entity.message.img.ImgReqMsg;
import com.mark.entity.message.text.TextReqMsg;
import com.mark.entity.message.voice.VoiceReqMsg;
import com.mark.entity.message.voice.VoiceRsqMsg;
import com.mark.util.MessageUtil;
import com.mark.util.XmlUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.CharEncoding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

/**
 * 微信入口controller
 *
 * @author maliqiang
 * @version 1.0
 * @create 2017-07-26
 */
@Controller
public class WechatController {
    private Logger log = LoggerFactory.getLogger(WechatController.class);

    /**
     * 校验信息是否是从微信服务器发过来的
     *
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @param response
     */
    @RequestMapping(value = "wechat", method = {RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    public void valid(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
                      @RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr, HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
//        boolean isGet = request.getMethod().toLowerCase().equals("get");
        try {

            out = response.getWriter();
            //将以上数据进行排序
            String[] str = {ConstantValue.TOKEN, timestamp, nonce};
            Arrays.sort(str); // 字典序排序
            String signStr = str[0] + str[1] + str[2];
            // SHA1加密
            String sign = DigestUtils.sha1Hex(signStr);
//            String digest = SignUtil.getDigestOfString(signStr.getBytes()).toLowerCase();
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature.equals(sign)) {// 验证成功返回ehcostr
                //原封不动回传微信服务器端消息给微信服务器，表示验证完成。此处非常重要。
                out.print(echostr);
                log.info("微信向你发来消息：" + echostr);
            } else {
                log.error("不是微信服务器发来的请求,请小心!");
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 微信消息的处理
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "wechat",method = {RequestMethod.POST}, produces = "text/xml;charset=UTF-8")
    public void reply2User(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setCharacterEncoding(CharEncoding.UTF_8);
        PrintWriter pw = response.getWriter();
        String wxMsgXml = IOUtils.toString(request.getInputStream(), CharEncoding.UTF_8);
        log.info("接收到的原始报文：" + wxMsgXml);
        String msgType = "text";
        TextReqMsg textReqMsg = null;
        ImgReqMsg imgReqMsg = null;
        VoiceReqMsg voiceReqMsg = null;
        try {
            //获取消息类型
            if (wxMsgXml != null) {
                msgType = XmlUtil.getMsgType(wxMsgXml,"MsgType");
            }
            log.info("接收到的微信请求消息类型：" + msgType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        StringBuffer replyMsg = new StringBuffer();
        //创建回复消息对象
        String returnXml = "";
        String rspMsg = "";
            // 增加你所需要的处理逻辑，这里只是简单重复消息
//			replyMsg.append("您给我的消息是：");
            /**
             * 根据类型处理回复消息
             */
            switch (msgType) {
                case MessageUtil.RESP_MESSAGE_TYPE_TEXT:
                    textReqMsg = XmlUtil.toBean(wxMsgXml, TextReqMsg.class);
                    returnXml = replyTextMsg4Req(textReqMsg);
                    rspMsg = MessageUtil.createTextRspMsg(textReqMsg, returnXml);
                    break;
                case MessageUtil.REQ_MESSAGE_TYPE_IMAGE:
                    imgReqMsg = XmlUtil.toBean(wxMsgXml, ImgReqMsg.class);
                    rspMsg = MessageUtil.createImgRspMsg(imgReqMsg);
                    break;
                case MessageUtil.REQ_MESSAGE_TYPE_VOICE:
                    voiceReqMsg = XmlUtil.toBean(wxMsgXml, VoiceReqMsg.class);
                    rspMsg = MessageUtil.createVoiceRspMsg(voiceReqMsg);
                    break;
                case MessageUtil.REQ_MESSAGE_TYPE_EVENT:
                    String eventType = XmlUtil.getMsgType(wxMsgXml,"Event");
                    String createTime = XmlUtil.getMsgType(wxMsgXml,"CreateTime");
                    String fromUser = XmlUtil.getMsgType(wxMsgXml,"FromUserName");
                    String toUserName = XmlUtil.getMsgType(wxMsgXml,"ToUserName");
                    rspMsg =MessageUtil.createEventRspMsg(eventType,fromUser,toUserName,createTime);
                    break;
            }

        log.info("回复消息：" + rspMsg);
        pw.write(rspMsg);
    }


    /**
     * 回复消息
     *
     * @param receivedMsg
     */
    private String replyTextMsg4Req(TextReqMsg receivedMsg) {
        StringBuffer replyMsg = new StringBuffer();
        if (receivedMsg.getContent().contains("帮助") || receivedMsg.getContent().contains("指南") || receivedMsg.getContent().contains("help")) {
            replyMsg.append(CommonMsg.HELP_DESC);
        }
        if (receivedMsg.getContent().contains("小李子")) {
            replyMsg.append("小李子好不容易获得了奥斯卡");
        } else if (receivedMsg.getContent().contains("知道")) {
            replyMsg.append("我当然知道了，我是万事通好不好");
        } else if (receivedMsg.getContent().contains("老马")) {
            replyMsg.append("欢迎访问，老马正在写程序,别打搅……");
        } else if (receivedMsg.getContent().contains("盼")) {
            replyMsg.append("欢迎来玩，送你一朵小花");
        } else {
            replyMsg.append("欢迎访问，我的小屋!");
        }
        return replyMsg.toString();
    }

//    /**
//     *
//     * @param imgReqMsg
//     * @return
//     */
//    private String replyImageMsg4Req(ImgReqMsg imgReqMsg) {
//        ImgRspMsg imgRspMsg = new ImgRspMsg();
//        imgRspMsg.setPicUrl(imgReqMsg.getPicUrl());
//        imgRspMsg.setMediaId(imgReqMsg.getMediaId());
//
//        imgReqMsg.setCreateTime();
//        imgReqMsg.setMessageType();
//        imgReqMsg.setFromUserName(imgReqMsg.getToUserName());
//        imgReqMsg.setToUserName(imgReqMsg.getFromUserName());
//        return null;
//    }

}